/**
 * 功能:各项辅助函数
 * 创建日期: 2012-03-16
 * 创建人: 全轩
 */

if(!this.Util)
{
	this.Util = {};
}

(function(){
		//获取url当中的参数
		Util.getQueryStringByName = function(url, name) {
			var result = url.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
	    	if (result == null || result.length < 1) {
	        	return "";
	    	}
	    	return result[1];
		}
		//将1700开始的时间搓,转换为本地时间
		Util.ConvertUTC2LocalDate = function(utcdate) {
			var tempDate = new Date(utcdate);
			tempDate.setHours(tempDate.getHours());
			var tempMinutes = ('00'+tempDate.getMinutes());
			var tempSeconds = ('00'+tempDate.getSeconds());
			var tempHours = ('00'+tempDate.getHours());
			var result = 
				tempDate.getFullYear() + '-' + 
				(tempDate.getMonth()+1)+ '-'  +   //格林时间为0~11月
				tempDate.getDate() + ' '  + 
				tempHours.substring(tempHours.length-2) + ':'  + 
				tempMinutes.substring(tempMinutes.length-2) + ':'  +
				tempSeconds.substring(tempSeconds.length-2) 
				
			return result;
		}
		
		Util.WeiboPlanform = function(weibohref)
		{
    		var result = />(\S+)<\/a>/.exec(weibohref)
	    	if (result == null || result.length < 1) {
	        	return '';
	    	}
	    	return result[1];
		}
		
		
		/**
		 * 记录当前homeline的最大微博id和最小微博id
		 */
		Util.SetHomeMaxidMinid = function(data)
		{
			if(data != null && data.length > 0)
			{
				SinaAuth.home_max_id = data[0].id;
				SinaAuth.home_min_id = data[data.length-1].id;
			}
		}
		/**
		 * 拍照,回传照片
		 */
		Util.ShowCamera = function(callback)
		{ 
			Titanium.Media.showCamera
			({
				success:function(event)
				{
					var image = event.media;
					callback(event.media);
				},
				cancel:function()
				{
				},
				error:function(error)
				{
				},
				showControls:true, 
				mediaTypes:Ti.Media.MEDIA_TYPE_PHOTO,
				autohide:true,
				transform: Titanium.UI.create2DMatrix().scale(2,2)  
			});
		}
		
		/*
		 * 格式化时间
		 */
		Util.FormatDate = function()
		{
			var date = new Date();
			var datestr = (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
			if (date.getHours()>=12)
			{
				datestr+=' '+(date.getHours()==12 ? date.getHours() : date.getHours()-12)+':'+date.getMinutes()+' PM';
			}
			else
			{
				datestr+=' '+date.getHours()+':'+date.getMinutes()+' AM';
			}
			return datestr;
		}
		
		/*
		 * 上下拖拽后自动加载的效果
		 */
		Util.HeaderPullView = function(tableView,callback)
		{
			var border = Ti.UI.createView({
				backgroundColor:"#576c89",
				height:2,
				bottom:0
			});
			
			var tableHeader = Ti.UI.createView({
				backgroundColor:"#e2e7ed",
				width:320,
				height:60
			});
			
			// fake it til ya make it..  create a 2 pixel
			// bottom border
			tableHeader.add(border);
			
			var arrow = Ti.UI.createView({
				backgroundImage:"../images/whiteArrow.png",
				width:23,
				height:60,
				bottom:10,
				left:20
			});
			
			var statusLabel = Ti.UI.createLabel({
				text:"拖动开始加载...",
				left:55,
				width:200,
				bottom:30,
				height:"auto",
				color:"#576c89",
				textAlign:"center",
				font:{fontSize:13,fontWeight:"bold"},
				shadowColor:"#999",
				shadowOffset:{x:0,y:1},
			});
			
			var lastUpdatedLabel = Ti.UI.createLabel({
				text:"最后更新时间: "+Util.FormatDate(),
				left:55,
				width:200,
				bottom:15,
				height:"auto",
				color:"#576c89",
				textAlign:"center",
				font:{fontSize:12},
				shadowColor:"#999",
				shadowOffset:{x:0,y:1},
			});
			
			var actInd = Titanium.UI.createActivityIndicator({
				left:20,
				bottom:13,
				width:30,
				height:30,
			});
			
			tableHeader.add(arrow);
			tableHeader.add(statusLabel);
			tableHeader.add(lastUpdatedLabel);
			tableHeader.add(actInd);
			
			var footerborder = Ti.UI.createView({
				backgroundColor:"#576c89",
				height:1,
				bottom:0,
			});
			
			var tableFooter = Ti.UI.createView({
				backgroundColor:"#e2e7ed",
				width:'100%',
				left:0,
				height:60,
			});
			
			// fake it til ya make it..  create a 2 pixel
			// bottom border
			tableFooter.add(footerborder);
			
			var footerarrow = Ti.UI.createView({
				backgroundImage:"images/whiteArrow.png",
				width:23,
				height:60,
				bottom:10,
				left:20
			});
			
			var footerstatusLabel = Ti.UI.createLabel({
				text:"拖动刷新...",
				left:55,
				width:200,
				bottom:30,
				height:"auto",
				color:"#576c89",
				textAlign:"center",
				font:{fontSize:13,fontWeight:"bold"},
				shadowColor:"#999",
				shadowOffset:{x:0,y:1}
			});
			
			var footerlastUpdatedLabel = Ti.UI.createLabel({
				text:"最后更新时间: "+Util.FormatDate(),
				left:55,
				width:200,
				bottom:15,
				height:"auto",
				color:"#576c89",
				textAlign:"center",
				font:{fontSize:12},
				shadowColor:"#999",
				shadowOffset:{x:0,y:1}
			});
			
			var footeractInd = Titanium.UI.createActivityIndicator({
				left:20,
				bottom:13,
				width:30,
				height:30
			});
			
			tableFooter.add(footerarrow);
			tableFooter.add(footerstatusLabel);
			tableFooter.add(footerlastUpdatedLabel);
			tableFooter.add(footeractInd);
			
			tableView.headerPullView = tableHeader;
			tableView.footerView = tableFooter;
			tableView.footerView.visible= true;
			
			var pulling = false;
			var reloading = false;
			var timeout = null;
			var isappend = false;
			
			function beginReloading(ifappend)
			{
				// just mock out the reload
				isappend = ifappend;
				timeout = setTimeout(endReloading,2000);
			}
			
			function endReloading()
			{
				// simulate loading
				if(isappend)
				{
					StatusesInfo.Get_Data_Next_Page(SinaAuth.home_min_id,20,callback);
									// when you're done, just reset
					tableView.setContentInsets({top:0},{animated:true});
					reloading = false;
					footerlastUpdatedLabel.text = "最后更新时间: "+Util.FormatDate();
					footerstatusLabel.text = "拖动开始刷新...";
					footeractInd.hide();
					footerarrow.show();
				}
				else
				{
					StatusesInfo.Get_Data_Prev_Page(SinaAuth.home_max_id,20,callback);
					
									// when you're done, just reset
					tableView.setContentInsets({top:0},{animated:true});
					reloading = false;
					lastUpdatedLabel.text = "最后更新时间: "+Util.FormatDate();
					statusLabel.text = "拖动开始刷新...";
					actInd.hide();
					arrow.show();
				}
			}
			
			tableView.addEventListener('scroll',function(e)
			{
				var offset = e.contentOffset.y;
				var offset2 = e.contentOffset.y + e.source.getHeight()  - e.contentSize.height;
				//Ti.API.info('offset:'+offset);
				//Ti.API.info('offset2:'+offset2);
				if (offset <= -65.0 && !pulling)
				{
					//Ti.API.info(1);
					var t = Ti.UI.create2DMatrix();
					t = t.rotate(-180);
					pulling = true;
					arrow.animate({transform:t,duration:180});
					statusLabel.text = "拖动后放开刷新...";
				}
				else if (pulling && offset > -65.0 && offset < 0)
				{
					//Ti.API.info(2);
					pulling = false;
					var t = Ti.UI.create2DMatrix();
					arrow.animate({transform:t,duration:180});
					statusLabel.text = "加载中...";
				}
				else if (offset2 >= 65.0 && !pulling)
				{
					//Ti.API.info(3);
					var t = Ti.UI.create2DMatrix();
					t = t.rotate(-180);
					pulling = true;
					footerarrow.animate({transform:t,duration:180});
					footerstatusLabel.text = "拖动后放开刷新...";
				}
				else if (pulling && offset2 <=65.0 && offset2 > 0)
				{
					pulling = false;
					var t = Ti.UI.create2DMatrix();
					footerarrow.animate({transform:t,duration:180});
					footerstatusLabel.text = "加载中...";
				}
			});
			
			tableView.addEventListener('scrollEnd',function(e)
			{
				if(!StatusWin.rows || StatusWin.rows.length == 0)
				{
					StatusWin.rows = e.source.data;
				}
				else if(StatusWin.rows.length != e.source.data.length)
				{
					StatusWin.rows = e.source.data;
				}
				
				Util.GetCurrentFirstRow(StatusWin.rows,e);
				
				if (pulling && !reloading)
				{
					reloading = true;
					pulling = false;
					
					if(e.contentOffset.y <= 0-65)
					{
						arrow.hide();
						actInd.show();
						statusLabel.text = "加载中...";
						tableView.setContentInsets({top:60},{animated:true});
						arrow.transform=Ti.UI.create2DMatrix();
						beginReloading(false);
						
						Util.GetCurrentFirstRow(StatusWin.rows,e);
					}
					else if(e.contentOffset.y + e.source.getHeight()  - e.contentSize.height > 65)
					{
						footerarrow.hide();
						footeractInd.show();
						footerstatusLabel.text = "加载中...";
						tableView.setContentInsets({top:60},{animated:true});
						footerarrow.transform=Ti.UI.create2DMatrix();
						beginReloading(true);
					}
				}
			});
		}
		/**
		 * 获取当前手机的经纬度值,依据经纬度值获取对应的位置信息
		 */
		Util.GetCurrentGeolocationInfo = function(callback)
		{
			var result = {};
			Ti.Geolocation.preferredProvider = "gps";
			Ti.Geolocation.purpose = '获取当前的位置,分享给我网友!';
			
			function translateErrorCode(code) {
				if (code == null) {
					return null;
				}
				switch (code) {
					case Ti.Geolocation.ERROR_LOCATION_UNKNOWN:
						return "Location unknown";
					case Ti.Geolocation.ERROR_DENIED:
						return "Access denied";
					case Ti.Geolocation.ERROR_NETWORK:
						return "Network error";
					case Ti.Geolocation.ERROR_HEADING_FAILURE:
						return "Failure to detect heading";
					case Ti.Geolocation.ERROR_REGION_MONITORING_DENIED:
						return "Region monitoring access denied";
					case Ti.Geolocation.ERROR_REGION_MONITORING_FAILURE:
						return "Region monitoring access failure";
					case Ti.Geolocation.ERROR_REGION_MONITORING_DELAYED:
						return "Region monitoring setup delayed";
				}
			}
			
			if (Titanium.Geolocation.locationServicesEnabled === false)
			{
				Titanium.UI.createAlertDialog({title:'易人提醒', message:'请打开定位服务!'}).show();
			}
			else
			{
					//
					//  TURN OFF ANNOYING COMPASS INTERFERENCE MESSAGE
					//
					Titanium.Geolocation.showCalibration = false;
			
					//
					// SET THE HEADING FILTER (THIS IS IN DEGREES OF ANGLE CHANGE)
					// EVENT WON'T FIRE UNLESS ANGLE CHANGE EXCEEDS THIS VALUE
					Titanium.Geolocation.headingFilter = 90;
			
					//
					//  GET CURRENT HEADING - THIS FIRES ONCE
					//
					Ti.Geolocation.getCurrentHeading(function(e)
					{
						if (e.error)
						{
							Ti.API.info("Code translation: "+translateErrorCode(e.code));
							return;
						}
						
						result.Heading = e;
						callback(result);
					});
			
					//
					// EVENT LISTENER FOR COMPASS EVENTS - THIS WILL FIRE REPEATEDLY (BASED ON HEADING FILTER)
					//
					var headingCallback = function(e)
					{
						if (e.error)
						{
							Ti.API.info("Code translation: "+translateErrorCode(e.code));
							return;
						}
			
						result.Heading = e;
						callback(result);
					};
					Titanium.Geolocation.addEventListener('heading', headingCallback);
			}
			
			//
			//  SET ACCURACY - THE FOLLOWING VALUES ARE SUPPORTED
			//
			// Titanium.Geolocation.ACCURACY_BEST
			// Titanium.Geolocation.ACCURACY_NEAREST_TEN_METERS
			// Titanium.Geolocation.ACCURACY_HUNDRED_METERS
			// Titanium.Geolocation.ACCURACY_KILOMETER
			// Titanium.Geolocation.ACCURACY_THREE_KILOMETERS
			//
			Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
		
			//
			//  SET DISTANCE FILTER.  THIS DICTATES HOW OFTEN AN EVENT FIRES BASED ON THE DISTANCE THE DEVICE MOVES
			//  THIS VALUE IS IN METERS
			//
			Titanium.Geolocation.distanceFilter = 10;
			
			//
			// GET CURRENT POSITION - THIS FIRES ONCE
			//
			Titanium.Geolocation.getCurrentPosition(function(e)
			{
				if (!e.success || e.error)
				{
					Ti.API.info("Code translation: "+translateErrorCode(e.code));
					return;
				}
				
				var longitude = e.coords.longitude;
				var latitude = e.coords.latitude;
				//Titanium.Geolocation.distanceFilter = 100; //changed after first location event
		
				// reverse geo
				Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
				{
					if (evt.success) {
						result.places = evt.places;
						callback(result);
						Ti.API.debug("reverse geolocation result = "+JSON.stringify(evt));
					}
					else {
						Ti.UI.createAlertDialog({
							title:'Reverse geo error',
							message:evt.error
						}).show();
						Ti.API.info("Code translation: "+translateErrorCode(e.code));
					}
				});
				
				result.location = e;
			});
			
			var locationCallback = function(e)
			{
				if (!e.success || e.error)
				{
					Ti.API.info("Code translation: "+translateErrorCode(e.code));
					return;
				}
				
				result.location = e;
				
				var longitude = e.coords.longitude;
				var latitude = e.coords.latitude;
				
				//Titanium.Geolocation.distanceFilter = 100; //changed after first location event
		
				// reverse geo
				Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
				{
					if (evt.success) {
						result.places = evt.places;
						callback(result);
					}
					else {
						Ti.UI.createAlertDialog({
							title:'Reverse geo error',
							message:evt.error
						}).show();
						
					}
				});
			};
			Titanium.Geolocation.addEventListener('location', locationCallback);
		}
		/**
		 * 获取当前滚动的TableView中,可见的第一行
		 */
		Util.GetCurrentFirstRow = function(rows,e)
		{
			var offsetHeight = e.contentOffset.y;
			
			for(var i=0;i<rows.length;i++)
			{
				
				offsetHeight = offsetHeight - rows[i].height;

				if(offsetHeight<0){
					StatusWin.firstrweetid= rows[i].id;
					break;
				}
				else if(offsetHeight>0 && rows[i+1] != undefined && offsetHeight < rows[i+1].height)
				{
					StatusWin.firstrweetid= rows[i+1].id;
					break;
				}
				else if(rows[i+1] == undefined)
				{
					StatusWin.firstrweetid= rows[i].id;
					break;
				}
				
			}
		}
		/**
		 * 生成微博列表titlecontrol
		 */
		Util.CreateTweetListTitleControl = function()
		{
			var titleControl = Ti.UI.createView({
					width:'100%',
					height:'100%',
					//backgroundImage:'images/login_bg.png',
				});
				
				//新增
				var btnWriteTweet = Ti.UI.createButton({
					backgroundImage:'images/header/title_new_normal.png',
					width:'20px',
					height:'19px',
					left:'5px',
				});
				titleControl.add(btnWriteTweet);
				
				//位置
				var btnLocaltion = Ti.UI.createButton({
					backgroundImage:'images/header/title_location_nor.png',
					width:'15px',
					height:'19px',
					left:'45px',
				});
				titleControl.add(btnLocaltion);
				
				//刷新
				var btnReflush = Ti.UI.createButton({
					backgroundImage:'images/header/title_reload_normal.png',
					width:'20px',
					height:'19px',
					right:'5px',
				});
				titleControl.add(btnReflush);
				
				return titleControl;
		}
		/**
		 * 生成直线
		 */
		Util.CreateLine = function(setting)
		{
			if(!setting)
			{
				setting = {};
				setting.height = '100%';
				setting.width = '1';
				setting.backgroundColor = '#000';
			}
			var line = Ti.UI.createView(setting);
			
			return line;
		}
		
		/**
		 * 生成悬浮框
		 */
		Util.CreateDiv = function(setting)
		{
			var mainView = Ti.UI.createView(setting);
			mainView.setting = setting;
			mainView.setLayout('absolute');
			
			mainView.addobj = function(obj)
			{
				mainView.add(obj);
				
				if(mainView.children != null && mainView.children.length>1)
				{
					var tempmainView = Ti.UI.createView(mainView.setting);
					var left = parseFloat(Ti.Platform.displayCaps.platformWidth)/mainView.children.length;
					for(var i =0 ;i<mainView.children.length;i++)
					{
						var item = mainView.children[i];
						var templeft =  left * (i+1);
						
						if(i<mainView.children.length-1)
						{
							var iii = Util.CreateLine({
								height:'100%',
								width:'1px',
								backgroundColor:'#000',
								left:templeft,
							});
							tempmainView.add(Util.CreateLine({
								height:'100%',
								width:'1px',
								backgroundColor:'#000',
								left:templeft,
							}));
						}

						var itemleft = left*i + (left - item.width)/2;
						item.setLeft(itemleft);
					
						tempmainView.add(item);
					}
					
					mainView = tempmainView;
				}
				
				return mainView;
			}
			
			return mainView;
		}

}())